package gazzera.node.core.plugins.upload;

import gazzera.node.core.*;
import gazzera.node.core.messages.*;

import java.io.*;


public class UploadDataPump implements DataPumpSource
{

	private File f;
	private long pos;
	private int toSend;
	private FileInputStream fis = null;

	public UploadDataPump(File f, long pos, int toSend)
	{
		super();
		this.f = f;
		this.pos = pos;
		this.toSend = toSend;
	}

	@Override
	public void finished(boolean interrupted) throws Exception
	{
		fis.close();		
	}

	@Override
	public void init() throws Exception
	{
		fis = new FileInputStream(f);
		fis.skip(pos);

	}

	@Override
	public Message next() throws Exception
	{
		int x = Math.min(5000, toSend);
		if (x < 1)
			return null; // finished
		byte[] b = new byte[x];  // TODO avoid this!!
		int r = fis.read(b);
		if (r != x)
			throw new Exception("Read x!=r");

		toSend -= r;

		return new ChunkData(b);
	}

}
